import java.util.Arrays;

public class Day48 {
//    [1,2,3,1]
//    [3,4,4,1]
//    [3,4,5,1]
    public static int[] clockwisePrint(int[][] mat, int n, int m) {
        int len = 0;
        if (m >= 2 && n >= 2) {
            len = m * 2 + (n-2) * 2;
        } else if (m == 1) {
            len = n;
        } else if (n == 1) {
            len = m;
        }
        // 结果数组
        int[] res = new int[len];
        // 打印第一行
        int index = 0;
        for (int i = 0; i < m; i ++) {
            res[index++] = mat[0][i];
        }
        // 只有一行
        if (n == 1) return res;
        // 打印右侧列
        for (int j = 1; j < n; j ++) {
            res[index++] = mat[j][m-1];
        }
        // 只有一列
        if (m == 1) return res;
        // 打印最后一行
        for (int k = m-2; k >= 0; k--) {
            res[index++] = mat[n-1][k];
        }
        // 打印左侧列
        for (int l = n-2; l > 0 ; l--) {
            res[index++] = mat[l][0];
        }
        return res;
    }

    public static int[] clockwisePrint2(int[][] mat, int n, int m) {
        // write code here
        //左上角坐标
        int x1 = 0;
        int y1 = 0;
        //右下角坐标
        int x2 = n - 1;
        int y2 = m - 1;
        int[] arr = new int[n * m];
        int idx = 0;
        while(x1 <= x2 && y1 <= y2)
        {
            //第一行: x1, y1 ~ y2
            for(int i = y1; i <= y2; ++i)
                arr[idx++] = mat[x1][i];
            //最后一列：x1 + 1 ~ x2, y2
            for(int i = x1 + 1; i <= x2; ++i)
                arr[idx++] = mat[i][y2];
            //最后一行：x2, y2 - 1, y1 --> x1 < x2
            if(x1 < x2)
            {
                for(int i = y2 - 1; i >= y1; --i)
                    arr[idx++] = mat[x2][i];
            }
            //第一列：x2 - 1 ~ x1 + 1, y1 --> y1 < y2
            if(y1 < y2)
            {
                for(int i = x2 - 1; i > x1; --i)
                    arr[idx++] = mat[i][y1];
            }
            x1++;
            y1++;
            x2--;
            y2--;
        }
        return arr;
    }

    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9},{0,1,2}};
        int[] res = clockwisePrint2(arr,4,3);
        System.out.println(Arrays.toString(res));
    }
}
